package us.kg.kotoriforest.springmvc.first.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import us.kg.kotoriforest.springmvc.first.pojo.User;

import java.io.File;
import java.io.IOException;

/**
 * @author Kotori rotroutine@163.com
 * @since 2025/2/4
 */
@RestController
public class RequestController {

    // username=kotori&password=123456&cellphone=1111111111&agreement=on
    // @RequestParam 可以用来获取请求参数 无论参数是在url中还是在请求体中都可以获取到
    // 请求参数有多个值时 可以使用数组或者集合接收
    @RequestMapping("/handle01")
    public String handle01(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("cellphone") String cellphone,
                           @RequestParam("agreement") boolean agreement) {
        System.out.println("username: " + username
                + ", password: " + password
                + ", cellphone: " + cellphone
                + ", agreement: " + agreement);
        return "handle01";
    }

    // 直接将请求参数封装到User对象中
    @RequestMapping("/handle03")
    public String handle03(User user) {
        System.out.println(user);
        return "handle03";
    }

    // 请求头不区分大小写
    @RequestMapping("/handle04")
    public String handle04(@RequestHeader("User-Agent") String userAgent) {
        System.out.println("User-Agent: " + userAgent);
        return "handle04";
    }

    @RequestMapping("/handle05")
    public String handle05(@CookieValue("Idea-ac70ee12") String cookie) {
        System.out.println("Idea-ac70ee12: " + cookie);
        return "handle05";
    }

    // username=kotori&
    // password=1223332331&
    // cellphone=dadadqeaafa&
    // address.province=江西&address.city=xx&address.area=yy&
    // sex=男&
    // hobby=足球&
    // grade=四年级&
    // agreement=on
    @RequestMapping("/handle06")
    public String handle06(User user) {
        System.out.println(user);
        return "handle06";
    }

    // 接收请求体中的json数据
    @RequestMapping("/handle07")
    public String handle07(@RequestBody User user) {
        System.out.println(user);
        return "handle07";
    }

    // 用@RequestPart接收请求体中的文件
    @RequestMapping("/handle08")
    public String handle08(@RequestPart("headerImg") MultipartFile headerImg,
                           @RequestPart("lifeImg") MultipartFile[] lifeImg) throws IOException {

        String headerImgName = headerImg.getOriginalFilename();

        headerImg.transferTo(new File("D:\\upload\\" + headerImgName));

        for (MultipartFile img : lifeImg) {
            String imgName = img.getOriginalFilename();
            img.transferTo(new File("D:\\upload\\" + imgName));
        }

        return "handle08";
    }

}
